package bean.managed;

import java.util.*;
import entity.InternalMessageEntity;
import entity.InternalMessageReceivedEntity;
import entity.SystemUserEntity;
import java.io.*;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import org.primefaces.event.ToggleEvent;
import org.primefaces.model.Visibility;
import type.MessageType;

@ManagedBean(name = "systemMessageController")
@SessionScoped
public class SystemMessageController extends UserMessageController implements Serializable {

    private InternalMessageEntity messageToToggle;

    public void prepareListSystemMessage(ToggleEvent event) {
        if (event.getVisibility().equals(Visibility.HIDDEN)) {
            return;
        }

        System.out.println("preparing to list..");
        populateInbox();
    }
    
    public void populateInbox() {
        if(getCurrentUser()==null)
            return;
        
        current = null;
        msgToUserInstance = new HashMap<InternalMessageEntity, InternalMessageReceivedEntity>();
        messageType = MessageType.SystemMessage;
        userManagedBean.isDisplaySystemMessageInbox();
        msg = userManagedBean.getSystemMessageInbox();
        markMessagesReadUnread();
        System.out.println("SystemMessage: populate inbox");
    }

    public String messageSelect() {
        System.out.println("Message Selected: " + selectedMessage);
        current = selectedMessage;

        return toggleReadAndUnread(current);
    }

    public InternalMessageEntity getMessageToToggle() {
        return messageToToggle;
    }

    public void setMessageToToggle(InternalMessageEntity messageToToggle) {
        this.messageToToggle = messageToToggle;
        toggleReadAndUnread(this.messageToToggle);
    }

    public String toggleReadAndUnread(InternalMessageEntity msg) {
        String redirectString = null;
        InternalMessageReceivedEntity msgInstance = msgToUserInstance.get(msg);
        if (!msgInstance.read()) {
            msgInstance.setOpenedAt(new Date());
            msg.setRead(true);
            redirectString = msg.getBody() + "?faces-redirect=true";
        } else {
            msgInstance.setOpenedAt(null);
            msg.setRead(false);
        }
        ejbFacade.editInternalMessageReceivedEntity(msgInstance);
        discardAndRediret();
        return redirectString;
    }
}
